import { useEffect, useState } from 'react';
import { apiCardDetailConvertOrder, apiCodeToOpenId, apiDecryptParam } from './api';
import Loading from './components/loading';
import main from './main';
import HomePage from './pages/homePage';
import { DetailJson } from './types';
import { copyToClipboard, decryptData, parseLocationParams } from './utils/utils';
let isWeixin = false;

export default function App() {
  const [openId, setopenId] = useState<string>();
  const [paramOrderId, setparamOrderId] = useState<string>();
  const [errorText, seterrorText] = useState<string>();
  const [detailData, setdetailData] = useState<DetailJson | undefined>();

  useEffect(() => {
    let ua = window.navigator.userAgent.toLowerCase();
    isWeixin = ua.includes('micromessenger');
    let uri = window.location.href;
    let redirect_uri = encodeURIComponent(uri);
    if (isWeixin && !window.location.search.includes('code') && !openId) {
      document.location.replace(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${main.appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
      );
    } else if (isWeixin && window.location.search.includes('code') && !openId) {
      let t = window.location.search.split('?')[1].split('&');
      let code = '';
      for (let s of t) {
        if (s.includes('code')) {
          code = s.split('=')[1];
          break;
        }
      }
      if (code) {
        main.code = code;
        getOpenId();
      }
    }
    if (openId) {
      main.openId = openId;
      setopenId(main.openId);
    }
    if (!isWeixin) {
      main.openId = '1';
      setopenId('1');
    }
  }, []); //eslint-disable-line

  useEffect(() => {
    // if (!openId) return;
    handUpdate();
  }, [openId]); //eslint-disable-line
  // 解密
  async function handUpdate() {
    let _p = parseLocationParams(window.location.search) ?? {};
    if (_p.q) {
      let res = await apiDecryptParam({ params: _p.q });
      let data = res.data;
      if (data.code === 200 && !!data.data) {
        let { orderId } = parseLocationParams(data.data);
        getDetailConvertOrder(orderId);
      } else {
        let { orderId } = parseLocationParams(decryptData(_p.q));
        getDetailConvertOrder(orderId);
      }
    } else if (_p.orderId) {
      getDetailConvertOrder(_p.orderId);
    }
  }
  // 获取openId
  async function getOpenId() {
    try {
      let uri = window.location.href;
      let redirect_uri = encodeURIComponent(uri);
      let res = await apiCodeToOpenId(main.code!, main.appId, redirect_uri);
      let data = res.data;
      if (data.code === 200) {
        main.openId = data.data?.openid || data.data?.openId;
        setopenId(main.openId);
      }
    } catch (e) {}
  }

  async function getDetailConvertOrder(orderId: string) {
    setparamOrderId(orderId);
    try {
      let res = await apiCardDetailConvertOrder(orderId);
      let data = res.data;
      if (data.code === 200) {
        let _data = data.data || {};
        setdetailData({
          ..._data,
          businessJson: JSON.parse(_data.businessJson ?? '{}'),
        });
      } else {
        setdetailData(undefined);
        seterrorText(data.msg ?? '获取失败，请联系客服人员');
      }
    } catch (e) {}
  }
  // function handUpdate() {
  //   let _p = parseLocationParams(window.location.search) ?? {};
  //   if (_p.q) {
  //     let { orderId } = parseLocationParams(decryptData(_p.q));
  //     getDetailConvertOrder(orderId);
  //   } else if (_p.orderId) {
  //     getDetailConvertOrder(_p.orderId);
  //   }

  // }
  function maskText(text: string, reg: RegExp = /^(.{3}).*?(.{2})$/, replaceReg: string = '$1*****$2') {
    return text.replace(reg, replaceReg);
  }
  function detailRender() {
    let item = (statusOptions ?? []).filter((item) => item.value === detailData?.orderStatus)[0];
    let isErrorStatus = detailData?.businessStatus === 'error';
    let address =
      (detailData?.provinceName ?? '') +
      (detailData?.cityName ?? '') +
      (detailData?.countyName ?? '') +
      (detailData?.receiverAddress ?? '');
    return (
      <div className="bw-100 bvh-100 d-flex-c ai-center">
        <div className="d-flex-r jc-center ai-center mt-60 border-bottom bw-100 pb-20">
          <img className="w-50" src={`./pic/${isErrorStatus ? 'icon_cancel' : item?.imgPath}.png`} alt="" />
          <span className="ml-20 font-widget-600 font-size-20">
            {isErrorStatus ? '提单失败，请联系客服' : item?.label}
          </span>
        </div>
        <div className="bw-100 mt-30">
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">充值卡号</div>
            {detailData?.iccid ? maskText(detailData?.iccid) : ''}
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">支付金额</div>
            {parseFloat(detailData?.payAmount ?? '0').toFixed(2)}
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">下单地址</div>
            <div className="flex-1">
              {maskText(address, /(.{12}).*/g, address.length > 12 ? '$1' + '*'.repeat(address.length - 12) : '')}
            </div>
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">状态</div>
            {isErrorStatus ? '异常单' : item?.label}
          </div>
          {isErrorStatus && (
            <div className="d-flex-r p-10 pl-20">
              <div className="w-80 font-widget-600 font-size-14">说明</div>
              {detailData?.businessRemark}
            </div>
          )}
          {detailData?.expressNum && (
            <div className="d-flex-r p-10 pl-20">
              <div className="w-80 font-widget-600 font-size-14">物流单号</div>
              <div className="text-color-blue">{detailData?.expressNum}</div>
              <span className="ml-20 text-color-blue" onClick={() => copyToClipboard(detailData.expressNum!)}>
                点击复制
              </span>
            </div>
          )}
          {detailData?.expressName && (
            <div className="d-flex-r p-10 pl-20">
              <div className="w-80 font-widget-600 font-size-14">物流名称</div>
              {detailData?.expressName}
            </div>
          )}
        </div>
      </div>
    );
  }
  if (!!errorText) {
    return (
      <div className="bw-100 bvh-100 d-flex-c ai-center jc-center">
        <div className="d-flex-c jc-center ai-center bw-100 pb-20">
          <img className="w-50 mb-20" src="./pic/icon_cancel.png" alt="" />
          <span className="ml-20 font-widget-600 font-size-20">{errorText}</span>
        </div>
      </div>
    );
  }
  if (!detailData && !errorText) {
    return (
      <Loading
        tips={'正在加载中...'}
        loadingClass="bh-100 overflow-hidden text-color-white d-flex-r ai-center jc-center mt-0 bg-shallow"
      />
    );
  }
  if (detailData?.orderStatus && detailData.orderStatus !== 1 && detailData.orderStatus !== 99) {
    return detailRender();
  }
  return <HomePage detailData={detailData!} paramOrderId={paramOrderId!} onUpdate={handUpdate} />;
}
const statusOptions = [
  { value: 5, label: '已取消', imgPath: 'icon_cancel' },
  { value: 3, label: '处理中', imgPath: 'icon_process' },
  { value: 2, label: '下单成功', imgPath: 'icon_success' },
  { value: 4, label: '已完结', imgPath: 'icon_end' },
  { value: 1, label: '待支付', imgPath: 'icon_end' },
];
